<template>
  <div class="sensitive-words-management">
    <div class="header">
      <h2>敏感词管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加敏感词
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="敏感词">
        <el-input v-model="searchForm.keyword" placeholder="请输入敏感词" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 敏感词表格 -->
    <el-table :data="wordList" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="word" label="敏感词" min-width="150" />
      <el-table-column prop="category" label="分类" min-width="120" />
      <el-table-column prop="level" label="敏感级别" width="120">
        <template #default="{ row }">
          <el-tag :type="getLevelTag(row.level)">
            {{ getLevelText(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="replace_word" label="替换词" min-width="150" />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 敏感词表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleClose"
    >
      <el-form ref="wordFormRef" :model="wordForm" :rules="wordRules" label-width="80px">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="wordForm.word" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="wordForm.category" />
        </el-form-item>
        <el-form-item label="敏感级别" prop="level">
          <el-select v-model="wordForm.level" placeholder="请选择敏感级别" style="width: 100%">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="替换词" prop="replace_word">
          <el-input v-model="wordForm.replace_word" placeholder="留空表示直接删除" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { formatDateTime } from '@/utils'
import { 
  getSensitiveWords, 
  createSensitiveWord, 
  updateSensitiveWord, 
  deleteSensitiveWord 
} from '@/api/system'
import type { SensitiveWord, SensitiveWordForm } from '@/api/system'

const loading = ref(false)
const dialogVisible = ref(false)
const isAdd = ref(true)
const wordFormRef = ref()

const searchForm = reactive({
  keyword: ''
})

const wordForm = reactive<SensitiveWordForm & { id?: number }>({
  id: undefined,
  word: '',
  category: '',
  level: 'medium',
  replace_word: ''
})

const wordList = ref<SensitiveWord[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const wordRules = {
  word: [{ required: true, message: '请输入敏感词', trigger: 'blur' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
  level: [{ required: true, message: '请选择敏感级别', trigger: 'change' }]
}

const dialogTitle = computed(() => isAdd.value ? '添加敏感词' : '编辑敏感词')

// 获取级别标签类型
const getLevelTag = (level: string) => {
  const tags = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return tags[level as keyof typeof tags] || 'warning'
}

// 获取级别文本
const getLevelText = (level: string) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return texts[level as keyof typeof texts] || level
}

// 获取敏感词列表
const fetchWords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.size,
      ...searchForm
    }
    
    const response = await getSensitiveWords(params)
    wordList.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取敏感词列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchWords()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { keyword: '' })
  pagination.current = 1
  fetchWords()
}

// 新增敏感词
const handleAdd = () => {
  isAdd.value = true
  Object.assign(wordForm, {
    word: '',
    category: '',
    level: 'medium',
    replace_word: ''
  })
  dialogVisible.value = true
}

// 编辑敏感词
const handleEdit = (row: SensitiveWord) => {
  isAdd.value = false
  Object.assign(wordForm, {
    id: row.id,
    word: row.word,
    category: row.category,
    level: row.level,
    replace_word: row.replace_word
  })
  dialogVisible.value = true
}

// 删除敏感词
const handleDelete = async (row: SensitiveWord) => {
  try {
    await ElMessageBox.confirm('确定删除该敏感词吗？', '提示', {
      type: 'warning'
    })
    
    await deleteSensitiveWord(row.id)
    ElMessage.success('删除成功')
    fetchWords()
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!wordFormRef.value) return
  
  try {
    const valid = await wordFormRef.value.validate()
    if (!valid) return
    
    if (isAdd.value) {
      // 创建时移除ID字段
      const { id, ...createData } = wordForm;
      await createSensitiveWord(createData);
      ElMessage.success('添加成功')
    } else {
      // 编辑时需要ID
      if (wordForm.id) {
        const { id, ...updateData } = wordForm;
        await updateSensitiveWord(id, updateData);
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error('编辑失败：缺少ID')
        return
      }
    }
    
    dialogVisible.value = false
    fetchWords()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  wordFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchWords()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchWords()
}

onMounted(() => {
  fetchWords()
})
</script>

<style scoped>
.sensitive-words-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>